package player

import (
	"GameServer/Common/utils"
	"fmt"

	"GameServer/Common/data"
	"GameServer/Game/errors"
	"GameServer/Game/lib"
	"GameServer/Game/m"
	"GameServer/Game/sp"

	log "github.com/sirupsen/logrus"
)

func (p *Player) StoryRewardRequest(req *sp.StoryRewardRequest) (res *sp.StoryRewardResponse, err error) {
	lockBlock := p.User.GetCurrentLockBlock()
	if lockBlock.Story.Status != 1 {
		res = &sp.StoryRewardResponse{
			Errcode: data.Errcode.ServerErr,
		}
		log.WithFields(log.Fields{
			"uid":    p.User.Uid.Hex(),
			"data":   lockBlock.Story,
			"method": "StoryRewardRequest",
		}).Error("故事绘本状态不为1")
		return res, nil
	}

	tpl, ok := data.Get("StoriesDraws", uint64(lockBlock.Story.Tid))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, fmt.Sprintf("没有找到故事绘配置信息：tid:%d", lockBlock.Story.Tid))
		res = &sp.StoryRewardResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}

	storyT := tpl.(data.StoriesDraw)

	giveGoods := make([]m.BaseKV, 0)

	for _, item := range storyT.Rewards {
		giveGoods = append(giveGoods, m.BaseKV{Key: int64(item.Key), Val: int64(item.Value)})
	}

	uProp, resGoodsList, boxRes, err := lib.GiveGoodsByKvList("StoryRewardRequest", p.User, giveGoods, p.Send)
	if err != nil {
		res = &sp.StoryRewardResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
	lockBlock.Story.Status = 2 // 已经领取奖励
	p.User.LockBlocks().UpdateLockBlock(lockBlock)
	res = &sp.StoryRewardResponse{
		Rewards: lib.FormatGoodsInfoSps(resGoodsList),
		BoxRes:  lib.FormatBoxResSps(boxRes),
		Story: &sp.Story{
			Tid:     lockBlock.Story.Tid,
			LayerId: lockBlock.Story.LayerId,
			Status:  lockBlock.Story.Status,
		},
	}

	if uProp != nil {
		p.TimelyUpdateProp(req.GetType(), uProp)
		utils.AsyncFunc(func() {
			p.UpdateProp(req.GetType(), uProp)
		})
	}
	return
}
